package com.youshang.nio;

import java.nio.ByteBuffer;
import java.util.stream.IntStream;

/**
 *  使用buffer 替换原用buffer中的属性
 *  SliceBuffer 与 原先buffer 共享底层数组
 * @author youshang
 * @date 2021/09/02 00:34
 **/
public class TestSlice {

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        //初始化 buffer 内容
        IntStream.range(0,10).forEach(i -> {
            buffer.put((byte) i);
        });

        //对buffer的内容进行部分获取
        buffer.position(3);
        buffer.limit(5);
        ByteBuffer sliceBuffer = buffer.slice();
        //对buffer的部分内容进行 处理
        for (int i = 0; i < sliceBuffer.capacity(); ++i) {
            byte b = sliceBuffer.get(i);
            b += 2;
            sliceBuffer.put(i,b);
        }

        //获取原先buffer 的全部内容
        buffer.position(0);
        buffer.limit(buffer.capacity());

        //循环输出
        while (buffer.hasRemaining()){
            System.out.println(buffer.get());
        }


    }
}
